import type { DATA, DBFUN } from '../db'
import { saveAs } from 'file-saver'
import dayjs from 'dayjs'

export class LocalStorageDB implements DBFUN {
    key = 'mock-data'
    
    constructor(dbKey: string, _dbName: string) {
        this.key = dbKey
    }
    setDB(data: DATA | DATA[]) {
        const json = window.localStorage.getItem(this.key)
        let dataList = json ? JSON.parse(json) : []
        if (Array.isArray(data)) {
            for (const d of data) {
                const index = dataList.findIndex(a => d.url === a.url && d.method === a.method && d.body === a.body)
                if (index !== -1) {
                    dataList[index] = d
                } else {
                    dataList = [ ...dataList, d ]
                }
            }
            window.localStorage.setItem(this.key, JSON.stringify(dataList))
        } else {
            const index = dataList.findIndex(d => d.url === data.url && d.method === data.method && d.body === data.body)
            if (index !== -1) {
                dataList[index] = data
            } else {
                dataList = [ ...dataList, data ]
            }
            window.localStorage.setItem(this.key, JSON.stringify(dataList))
        }
    }
    getDB(): Promise<DATA[]> {
        return new Promise((resolve, reject) => {
            const json = window.localStorage.getItem(this.key)
            resolve(json ? JSON.parse(json) : [])
        })
    }
    clear() {
        window.localStorage.setItem(this.key, '')
    }
    async downloadDBJson(fn?: (data: DATA[]) => any[]) {
        const list = await this.getDB()
        if (list.length > 0) {
            const l = fn ? fn(list) : list;
            const file = new File([JSON.stringify(l)], `mock.${dayjs().format('YYYY-MM-DD HH:mm:ss')}.json`, {type: "text/plain;charset=utf-8"})
            saveAs(file)
        } else {
            console.error('未捕捉到任何接口数据')
        }
    }
}
